const remote = require('electron').remote;
const curWin = remote.getCurrentWindow();
const fs = require('fs');
const path = require('path');
const windowListId = remote.getGlobal("Window_List_Id");
new Vue({
  el: document.getElementById("root"),
  data: {
    projectName: '',
    host: '',
    port: '',
    baseUrl: ''
  },
  methods: {
    onSubmit() {
      if (this.projectName !== '' && this.isDirName(this.projectName)) {
        const dir = path.resolve("/data-mock/projects", this.projectName);
        fs.mkdir(dir, { recursive: true }, err => {
          if (err) {
            if (fs.statSync(dir).isDirectory()) {
              //文件夹存在
            }
          } else {
            const project = {
              projectName: this.projectName,
              host: this.host,
              port: this.port,
              baseUrl: this.baseUrl,
              javascript: "",
              mocks: {
                string: {},
                regx: []
              }
            };
            if (project.baseUrl.charAt(0) !== '/') project.baseUrl = '/' + project.baseUrl;
            fs.writeFile(path.join(dir, `${this.projectName}.json`), JSON.stringify(project, null, 4), err => {
              if (err) throw err;
              remote.BrowserWindow.fromId(windowListId).webContents.send("pushProject", project);
              fs.copyFileSync(path.resolve(__dirname, '../../../template/template.js'), path.join(dir, 'server.js'));
              fs.copyFileSync(path.resolve(__dirname, '../../../template/mock.min.js'), path.join(dir, 'mock.js'));
              curWin.close();
            });
          }
        })
      } else {
        //项目名称不合适
      }
    },
    onCancel() {
      curWin.close();
    },
    isDirName(name) {
      return !/<|>|\/|\:|\*|\?/.test(name);
    }
  }
});
